package cn.licoy.wdog.core.controller.hospital;

import cn.licoy.wdog.common.annotation.SysLogs;
import cn.licoy.wdog.common.bean.ResponseCode;
import cn.licoy.wdog.common.bean.ResponseResult;
import cn.licoy.wdog.common.exception.RequestException;
import cn.licoy.wdog.common.util.ExportDetectionInfo;
import cn.licoy.wdog.common.util.Tools;
import cn.licoy.wdog.core.config.jwt.JwtToken;
import cn.licoy.wdog.core.dto.hospitalUser.DetectionInfoDto;
import cn.licoy.wdog.core.dto.hospitalUser.PageDto;
import cn.licoy.wdog.core.entity.hospital.DetectionInfo;
import cn.licoy.wdog.core.entity.hospital.HospitalUser;
import cn.licoy.wdog.core.service.hospital.DetectionInfoService;
import cn.licoy.wdog.core.service.hospital.HospitalUserService;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;


/**
 * @author Sunne
 * Create time 2018/6/22 17:38
 * @return null
 **/
@RestController
@RequestMapping(value = "/hospitaluser")
@Api(tags = {"第一期--检测结果处理"})
public class DetectionInfoController {
    @Autowired
    DetectionInfoService detectionInfoService;
    @Autowired
    HospitalUserService hospitalUserService;

    @PostMapping(value = {"/add"})
    @ApiOperation(value = "数据上传")
    @SysLogs("数据上传")
    @ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
    public ResponseResult verificationCode(@RequestBody  @Validated @ApiParam(value = "检测数据") DetectionInfoDto dto){
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        boolean b = Tools.executeLogin(request);
        if(!b){
            throw RequestException.fail("身份已过期或无效，请重新认证");
        }
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            throw new RequestException(ResponseCode.NOT_SING_IN);
        }
        JwtToken jwtToken = new JwtToken();
        Object principal = subject.getPrincipal();
        if(principal==null){
            throw RequestException.fail("用户信息获取失败");
        }
        BeanUtils.copyProperties(principal,jwtToken);
        HospitalUser user = hospitalUserService.findUserByName(jwtToken.getUsername(),false);
        if(user==null){
            throw RequestException.fail("用户不存在");
        }

        detectionInfoService.add(dto,user.getId());
        return ResponseResult.e(ResponseCode.OK,"操作成功");
    }

    @PostMapping(value = {"/selectToCondition"})
    @ApiOperation(value = "按单一条件分页查询数据")
    @SysLogs("按单一条件分页查询数据")
    @ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
    public ResponseResult<Page<DetectionInfo>> selectToException(@RequestBody  @Validated @ApiParam(value = "分页依据和参数") PageDto pageDto){
        Page<DetectionInfo> pa = null;
        HospitalUser user = this.getuserInfo();
        if(!"".equals(pageDto.getSerialNum())&&pageDto.getSerialNum()!=null){
            //按体检编号查询
            String field = "serial_num";
            pa = detectionInfoService.selectToCondition(pageDto.getSerialNum(),field,pageDto.getCurrentPage(),pageDto.getPageSize(),user.getId());
        }else
        if (!"".equals(pageDto.getUsername())&&pageDto.getUsername()!=null){
            //按用户名查询
            String field = "username";
            pa = detectionInfoService.selectToCondition(pageDto.getUsername(),field,pageDto.getCurrentPage(),pageDto.getPageSize(),user.getId());
        }else
        if ((!"".equals(pageDto.getStartime())&&pageDto.getStartime()!=null)&&
                (!"".equals(pageDto.getEndTime())&&pageDto.getEndTime()!=null)){
            //按时间查询
            String field = "detection_date";
            pa = detectionInfoService.selectToDate(pageDto.getStartime(),pageDto.getEndTime(),pageDto.getCurrentPage(),pageDto.getPageSize(),user.getId());
        }else
        if (!"".equals(pageDto.getRegion())&&pageDto.getRegion()!=null){
            //按地区查询
            String field = "region";
            pa = detectionInfoService.selectToCondition(pageDto.getRegion(),field,pageDto.getCurrentPage(),pageDto.getPageSize(),user.getId());
        }else
        if(!"".equals(pageDto.getGender())&&pageDto.getGender()!=null){
            //按性别查询
            String field = "gender";
            pa = detectionInfoService.selectToCondition(pageDto.getGender(),field,pageDto.getCurrentPage(),pageDto.getPageSize(),user.getId());
        }else
        if (!"".equals(pageDto.getIsException())&&pageDto.getIsException()!=null){
            //是否异常查询
            String field = "is_exception";
            pa = detectionInfoService.selectToCondition(pageDto.getIsException(),field,pageDto.getCurrentPage(),pageDto.getPageSize(),user.getId());
        }else{
            pa = detectionInfoService.selectToAll(pageDto,user.getId());
        }

        return ResponseResult.e(ResponseCode.OK,pa);
    }
//    @PostMapping(value = {"/selectToDate"})
//    @ApiOperation(value = "按时间查询检测数据")
//    @SysLogs("按时间查询检测数据")
//    @ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
//    public ResponseResult<Page<DetectionInfo>> selectToDate(@RequestBody  @Validated @ApiParam(value = "分页依据和参数") PageDto pageDto){
//
//        Page<DetectionInfo> pa = detectionInfoService.selectToDate(pageDto);
//        return ResponseResult.e(ResponseCode.OK,pa);
//    }
    @GetMapping(value = {"/export"})
    @ApiOperation(value = "导出指定用户的检查数据")
    //    @SysLogs("导出指定用户的检查数据")
    //    @ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
    public void export(@ApiParam(value = "需要导出的数据的id集合") @RequestParam String[] ids, HttpServletResponse response, HttpServletRequest request){
        List<DetectionInfo> detectionInfoList = new ArrayList<>();
        for (String id: ids) {
            DetectionInfo detectionInfo = detectionInfoService.selectById(id);
            detectionInfoList.add(detectionInfo);
        }
        HSSFWorkbook wb = ExportDetectionInfo.getHSSFWorkbook(detectionInfoList);
        //响应到客户端
        try {
            //web浏览通过MIME类型判断文件是excel类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");

            // 对文件名进行处理。防止文件名乱码
            String fileName = new String("尿液分析报告单.xls".getBytes(),"ISO8859-1");
            // Content-disposition属性设置成以附件方式进行下载
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/list")
    @ApiOperation(value = "检测结果列表")
    @SysLogs("检测结果列表")
    @ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
    public  ResponseResult<Page<DetectionInfo>> detectionInfoList(@RequestBody  @Validated @ApiParam(value = "分页依据和参数") PageDto pageDto){ HospitalUser user = this.getuserInfo();
        Page<DetectionInfo> pa = detectionInfoService.selectToAll(pageDto,user.getId());
        return ResponseResult.e(ResponseCode.OK,pa);
    }

    @PostMapping(value = {"/findReginByUsername"})
    @ApiOperation(value = "获取该账户检测的所有的地区")
    @SysLogs("获取该账户检测的所有的地区")
    @ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
    public ResponseResult<List<String>> findReginByUsername(){
        HospitalUser user = this.getuserInfo();
        List<String> ls = detectionInfoService.findReginByUsername(user);
        return ResponseResult.e(ResponseCode.OK,ls);
    }
    /**
     * 获取用户信息
     * */
    public HospitalUser getuserInfo(){
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        boolean b = Tools.executeLogin(request);
        if(!b){
            throw RequestException.fail("身份已过期或无效，请重新认证");
        }
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            throw new RequestException(ResponseCode.NOT_SING_IN);
        }
        JwtToken jwtToken = new JwtToken();
        Object principal = subject.getPrincipal();
        if(principal==null){
            throw RequestException.fail("用户信息获取失败");
        }
        BeanUtils.copyProperties(principal,jwtToken);
        HospitalUser user = hospitalUserService.findUserByName(jwtToken.getUsername(),false);
        if(user==null){
            throw RequestException.fail("用户不存在");
        }else {
            return user;
        }

    }
}
